<template>
  <div class="">
    <h1>商品信息</h1>
    <table width="1000" border="1" cellspacing="0">
      <tr>
        <th>id</th>
        <th>名称</th>
        <th>价格</th>
        <th>数量</th>
        <th>操作</th>
      </tr>
      <tr v-for="(item, index) in shoplist" :key="item.id">
        <td>{{ item.id }}</td>
        <td>{{ item.name }}</td>
        <td>{{ item.price }}</td>
        <td>{{ item.count > 0 ? item.count : "" }}</td>
        <td>
          <button v-if="item.count <= 0" @click="add(index)">加入购物车</button>
          <div v-else>
            <button @click="add(index)">+</button>
            <button @click="min(index)">-</button>
          </div>
        </td>
      </tr>
    </table>

    <h1>购物车信息</h1>

    <table width="1000" border="1" cellspacing="0">
      <tr>
        <th>id</th>
        <th>名称</th>
        <th>价格</th>
        <th>数量</th>
        <th>操作</th>
      </tr>
      <tr
        v-for="(item, index) in shoplist"
        :key="item.id"
        v-show="item.count > 0"
      >
        <td>{{ item.id }}</td>
        <td>{{ item.name }}</td>
        <td>{{ item.price }}</td>
        <td>{{ item.count }}</td>
        <td>
          <div>
            <button @click="add(index)">+</button>
            <button @click="min(index)">-</button>
            <button @click="remove(index)">x</button>
          </div>
        </td>
      </tr>
    </table>

    <footer>
      总数：{{ obj.count }},总价:{{ obj.price }}
      <button @click="clear">清空购物车</button>
    </footer>
  </div>
</template>

<script>
export default {
  data() {
    return {
      shoplist: [],
    };
  },
  mounted() {
    this.$axios.get("data.json").then((res) => {
      console.log(res);
      this.shoplist = res.data.productsData;
    });
    //进入页面请求购物车数据
  },
  methods: {
    add(index) {
      this.shoplist[index].count++;
    },
    //添加购物车
    min(index) {
      this.shoplist[index].count--;
    },
    //减少购物车数量
    remove(index) {
      this.shoplist[index].count = 0;
    },
    //从购物车中删除这条数据
    clear() {
      this.shoplist.forEach((item) => {
        item.count = 0;
      });
    },
    //清空购物车
  },
  components: {},
  computed: {
    obj() {
      let count = 0;
      let price = 0;
      this.shoplist.forEach((item) => {
        count += item.count;
        price += item.count * item.price;
      });
      return { count, price };
    },
    //对总数和总价进行计算 计算属性可以返回一个对象或者数组 这样就可以在一个计算属性中计算多个值
  },
};
</script>

<style lang="scss"></style>
